import React, { useEffect, useState } from 'react';
import { message, Space, Popconfirm } from 'antd';
import { Button } from '@/components/eai-design';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Search } from '@/components/eai-design';
import Tables from '@/components/tables/tables';
import Modals from '@/components/modals/Modals';
import nl2sqlService from '@/api/services/nl2sqlService';
import { CaseInfo } from '@/types/nl2sql/type';

interface CaseManagementProps {
  knowledgeId: string;
}

const CaseManagement: React.FC<CaseManagementProps> = ({ knowledgeId }) => {
  const [searchValue, setSearchValue] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingCase, setEditingCase] = useState<CaseInfo | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
  });
  
  // 分页状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取案例列表
  const { data: cases = [], loading, refresh } = useRequest(
    async () => {
      const res = await nl2sqlService.getCases(knowledgeId);
      return res.databaseInfos || [];
    },
    {
      refreshDeps: [knowledgeId],
    }
  );

  // 创建案例
  const { runAsync: createCase, loading: createLoading } = useRequest(
    (data: { knowledge_id: string; name: string; description: string }) =>
      nl2sqlService.createCase(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('创建案例成功');
        setIsModalVisible(false);
        resetForm();
        refresh();
      },
      onError: (error) => {
        // message.error('创建案例失败');
        console.error('创建案例失败:', error);
      },
    }
  );

  // 更新案例
  const { runAsync: updateCase, loading: updateLoading } = useRequest(
    (data: { knowledge_id: string; name: string; description: string; data_id: string }) =>
      nl2sqlService.updateCase(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('更新案例成功');
        setIsModalVisible(false);
        resetForm();
        refresh();
      },
      onError: (error) => {
        // message.error('更新案例失败');
        console.error('更新案例失败:', error);
      },
    }
  );

  // 删除案例
  const { runAsync: deleteCase, loading: deleteLoading } = useRequest(
    (data: { knowledge_id: string; name: string; description: string; data_id: string }[]) =>
      nl2sqlService.deleteCase(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('删除案例成功');
        refresh();
        setSelectedRowKeys([]);
      },
      onError: (error) => {
        // message.error('删除案例失败');
        console.error('删除案例失败:', error);
      },
    }
  );

  // 批量删除案例
  const { runAsync: batchDeleteCases, loading: batchDeleteLoading } = useRequest(
    async () => {
      // 构建要删除的案例列表
      const casesToDelete = selectedRowKeys
        .map((key) => {
          const caseItem = cases.find((c) => c.data_id === key);
          if (caseItem && caseItem.data_id) {
            return {
              knowledge_id: caseItem.knowledge_id,
              name: caseItem.name,
              description: caseItem.description,
              data_id: caseItem.data_id,
            };
          }
          return null;
        })
        .filter((caseItem): caseItem is { knowledge_id: string; name: string; description: string; data_id: string } =>
          caseItem !== null
        ); // 类型守卫过滤掉 null 值

      if (casesToDelete.length > 0) {
        // 直接调用批量删除接口，传递整个列表
        await deleteCase(casesToDelete);
      }
    },
    {
      manual: true,
      onSuccess: () => {
        // message.success('批量删除成功');
        setSelectedRowKeys([]);
      },
    }
  );

  // 分页处理函数
  const handlePaginationChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    // 分页变化时清空选中状态，避免跨页选择问题
    setSelectedRowKeys([]);
  };

  // 过滤表格数据
  const filteredCases = cases?.filter((caseItem: CaseInfo) => {
    if (!searchValue) return true;
    return (
      caseItem.name.toLowerCase().includes(searchValue.toLowerCase()) ||
      caseItem.description.toLowerCase().includes(searchValue.toLowerCase())
    );
  });

  // 计算分页后的数据（如果分页后无数据且当前页不为1，则自动跳转到上一页）
  const paginatedCases = React.useMemo(() => {
    const data = filteredCases?.slice((currentPage - 1) * pageSize, currentPage * pageSize) || [];
    if (data.length === 0 && currentPage > 1) {
      // 自动跳转到上一页
      setCurrentPage(currentPage - 1);
      return filteredCases?.slice((currentPage - 2) * pageSize, (currentPage - 1) * pageSize) || [];
    }
    return data;
  }, [filteredCases, currentPage, pageSize]);

  // 重置表单
  const resetForm = () => {
    setFormData({ name: '', description: '' });
    setEditingCase(null);
  };

  // 打开新增模态框
  const handleAdd = () => {
    setIsModalVisible(true);
    setEditingCase(null);
    resetForm();
  };

  // 打开编辑模态框
  const handleEdit = (record: CaseInfo) => {
    setEditingCase(record);
    setFormData({
      name: record.name,
      description: record.description,
    });
    setIsModalVisible(true);
  };

  // 处理删除
  const handleDelete = (record: CaseInfo) => {
    if (record.data_id) {
      deleteCase([{
        knowledge_id: record.knowledge_id,
        name: record.name,
        description: record.description,
        data_id: record.data_id,
      }]);
    }
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的案例');
      return;
    }
    batchDeleteCases();
  };

  // 处理表单提交
  const handleSubmit = () => {
    if (!formData.name.trim()) {
      message.warning('请输入问法描述');
      return;
    }
    if (!formData.description.trim()) {
      message.warning('请输入预期正确执行的SQL语句');
      return;
    }

    if (editingCase) {
      // 更新案例
      if (editingCase.data_id) {
        updateCase({
          knowledge_id: editingCase.knowledge_id,
          name: formData.name.trim(),
          description: formData.description.trim(),
          data_id: editingCase.data_id,
        });
      }
    } else {
      // 创建案例
      createCase({
        knowledge_id: knowledgeId,
        name: formData.name.trim(),
        description: formData.description.trim(),
      });
    }
  };

  // 处理模态框关闭
  const handleModalClose = () => {
    setIsModalVisible(false);
    resetForm();
  };

  // 表格列定义
  const columns = [
    {
      title: '问法描述',
      dataIndex: 'name',
      width: 200,
      key: 'name',
      render: (text: string) => (
        <span className="text-blue-600 font-medium">{text}</span>
      ),
    },
    {
      title: '预期正确执行的SQL语句',
      dataIndex: 'description',
      width: 200,
      key: 'description',
      ellipsis: true,
      render: (text: string) => (
        <div className="font-mono text-sm bg-gray-50 p-2 rounded">
          {text}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: CaseInfo) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            className="text-blue-600 hover:text-blue-800"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个案例吗？"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              className="text-red-600 hover:text-red-800"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    // 添加全选/取消全选功能
    onSelectAll: (selected: boolean, selectedRows: CaseInfo[], changeRows: CaseInfo[]) => {
      if (selected) {
        // 只选择当前页的数据
        const currentPageKeys = paginatedCases.map(item => item.data_id as React.Key);
        setSelectedRowKeys(currentPageKeys);
      } else {
        setSelectedRowKeys([]);
      }
    },
  };

  useEffect(() => {
    setCurrentPage(1);
    setPageSize(10);
  }, [knowledgeId]);

  return (
    <div className="flex-1 flex flex-col h-full">
      {/* 搜索栏 */}
      <div className="mb-4 px-4 pt-4">
        <Search
          placeholder="搜索"
          className="w-full max-w-sm"
          allowClear
          value={searchValue}
          onChange={(e) => {
            setSearchValue(e.target.value);
            // 搜索时重置分页状态
            setCurrentPage(1);
            setSelectedRowKeys([]);
          }}
        />
      </div>

      {/* 操作按钮 */}
      <div className="mb-4 px-4 flex items-center justify-end">
        <div className="flex items-center gap-2 justify-end mr-2">
          {selectedRowKeys.length > 0 && (
            <>
              <span className="text-sm text-text-5">
                已选择 {selectedRowKeys.length} 项
              </span>
              <Button
                onClick={() => setSelectedRowKeys([])}
                className="text-gray-500"
              >
                取消
              </Button>
              <Popconfirm
                title={`确定要删除选中的 ${selectedRowKeys.length} 个案例吗？`}
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  loading={batchDeleteLoading}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          )}
        </div>
        <Button
          type="secondary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
          className="bg-blue-500 hover:bg-blue-600"
        >
          新增案例
        </Button>
      </div>

      {/* 案例列表 */}
      <div className="flex-1 overflow-hidden px-4 h-full">
        <Tables
          columns={columns}
          dataSource={paginatedCases}
          rowKey="data_id"
          loading={loading}
          rowSelection={rowSelection}
          paginationProps={{
            total: filteredCases.length,
            current: currentPage,
            pageSize: pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: handlePaginationChange,
          }}
          // scroll={{ y: 'calc(100vh - 400px)' }}
        />
      </div>

      {/* 新增/编辑案例模态框 */}
      <Modals
        title={editingCase ? '编辑案例' : '新增案例'}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={handleModalClose}
        confirmLoading={createLoading || updateLoading}
        onClose={handleModalClose}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              问法描述
            </label>
            <input
              type="text"
              placeholder="请输入问题"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              预期正确执行的SQL语句
            </label>
            <textarea
              placeholder="请输入预期正确执行的SQL语句"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              rows={6}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none font-mono"
            />
          </div>
        </div>
      </Modals>
    </div>
  );
};

export default CaseManagement; 